package com.central.dataManage.controller;


import com.central.common.annotation.RequiredPermission;
import com.central.common.constant.PermissionConstants;
import com.central.common.enums.DbType;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.common.model.DatasourceInfo;
import com.central.dataManage.common.utils.CommonUtils;
import com.central.dataManage.service.IDatasourceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @author Tindy
 * @date 2021/6/24
 * @describe
 */
@Slf4j
@RestController
@Api(tags = "数据源管理")
@RequestMapping(value = "/datasource")
public class DatasourceManageController {

    @Autowired
    private IDatasourceService datasourceService;

    /**
     * 新增或修改数据源
     *
     * @return
     */
    @ApiOperation(value = "新增或修改数据源")
    @CacheEvict(value = "datasourceList",allEntries = true)
    @PostMapping("/addOrUpdate")
    @RequiredPermission(PermissionConstants.GLO_DATA_ADMIN)
    public Result addOrUpdate(@RequestBody DatasourceInfo datasourceInfo) throws Exception {
        return datasourceService.saveOrUpdateDatasource(datasourceInfo);
    }

    /**
     * 数据源查询
     *
     * @return
     */
    @ApiOperation(value = "数据源列表,分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页起始位置", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "limit", value = "分页结束位置", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "datasourceType", value = "数据源类型", required = false, dataType = "String"),
            @ApiImplicitParam(name = "name", value = "数据源名称", required = false, dataType = "String")
    })
    @GetMapping("/findDatasources")
    public PageResult<DatasourceInfo> findDatasources(@RequestParam Map<String, Object> params) {
        return datasourceService.findDatasources(params);
    }

    /**
     * 数据源查询
     *
     * @return
     */
    @ApiOperation(value = "数据源查询by id,密码不脱敏")
    @GetMapping("/pv/find/{id}")
    public DatasourceInfo findById(@PathVariable Long id) {
        DatasourceInfo datasourceInfo = datasourceService.getById(id);
        return datasourceInfo;
    }

    /**
     * 删除数据源
     *
     * @param id
     */
    @ApiOperation(value = "删除数据源by id")
    @CacheEvict(value = {"datasourceList"},allEntries = true)
    @DeleteMapping(value = "/delete/{id}")
    @RequiredPermission(PermissionConstants.GLO_DATA_ADMIN)
    public Result delete(@PathVariable Long id) {
        try {
            datasourceService.delById(id);
            return Result.succeed("操作成功");
        } catch (Exception ex) {
            log.error("datasource-del-error", ex);
            return Result.failed("操作失败");
        }
    }

    /**
     * 数据源连通测试
     *
     * @return
     */
    @ApiOperation(value = "数据源连通测试")
    @PostMapping("/connTest")
    public Result<String> connTest(@RequestBody DatasourceInfo datasourceInfo) {
        if (datasourceInfo.getId() != null) {
            datasourceInfo = datasourceService.getById(datasourceInfo.getId());
        }else {
            datasourceInfo.setPassword(CommonUtils.encodePassword(datasourceInfo.getPassword()));
        }
        boolean flag = datasourceService.connTest(datasourceInfo);
        if (flag) {
            return Result.succeed("连接成功");
        } else {
            return Result.failed("连接失败");
        }
    }

    /**
     * 元数据同步
     *
     * @return
     */
    @ApiOperation(value = "元数据同步")
    @CacheEvict(value = "databaseList",key = "#id")
    @GetMapping("/synch/{id}")
    @RequiredPermission(PermissionConstants.GLO_DATA_ADMIN)
    public Result<String> synch(@PathVariable Long id) throws SQLException {
        boolean flag = datasourceService.synch(id);
        if (flag) {
            return Result.succeed("同步成功");
        } else {
            return Result.failed("同步失败");
        }
    }

    /**
     * 根据数据源类型，查询数据源
     *
     * @return
     */
    @ApiOperation(value = "根据数据源类型，查询数据源列表")
    @GetMapping("/datasourcesByType/{type}")
    public Result<List<Map<String,Object>>> datasourceByType(@PathVariable DbType type) {
        List<Map<String,Object>> dmDatasources = datasourceService.datasourcesByType(type);
        return Result.succeed(dmDatasources);
    }

    @ApiOperation(value = "数据源类型")
    @GetMapping("/findAllDbTypes")
    public List<DbType> findAllDbTypes(){
        return datasourceService.findAllDbTypes();
    }
}
